package com.bigstar.lolen_e;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.AssetManager.AssetInputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class Lolkor extends Activity implements OnClickListener{
    public static int[] rota_index = new int[10];
    /** Called when the activity is first created. */
    @Override
    protected void onResume() {
        ChampionData.load(this);
    	super.onResume();
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
        for(int i = 0; i < rota_index.length; i++){
        	rota_index[i] = -1;
        }

        ChampionData.load(this);
        setContentView(R.layout.main);
        AdView adview = (AdView)findViewById(R.id.adView);
        AdRequest re = new AdRequest(); 
        adview.loadAd(re);
        Button button = (Button)findViewById(R.id.champion_info);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.item_info);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.mastery_info);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.spells_info);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.champ_gallery);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.server_status);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.builder);
        button.setOnClickListener(this);
        button = (Button)findViewById(R.id.jugle_timer);
        button.setOnClickListener(this);
        
        button = (Button)findViewById(R.id.option);
        button.setOnClickListener(this);

        button = (Button)findViewById(R.id.ranking);
        button.setOnClickListener(this);    
        SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		boolean notice = pref.getBoolean("notice", false);
		String notice_name = "League of Legends v1.0.0.151";
        if(!notice){
            String anno = null;
    		try {
    			anno = loadUpdate();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		HistoryDialog hd = new HistoryDialog(this, notice_name, anno);
    		hd.show();	
        }else{
        	Date today = new Date();
            SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");       
    		int notice_date = pref.getInt("notice_date", 0);
    		int today_date = Integer.parseInt(formater.format(today));
    		if(today_date > notice_date){
    			SharedPreferences.Editor editor = pref.edit();
    			editor.putInt("notice_date", today_date);
    			editor.commit();
    	        String anno = null;
    			try {
    				anno = loadUpdate();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			HistoryDialog hd = new HistoryDialog(this, notice_name, anno);
    			hd.show();
    		}
        }
		
		Thread t = new Thread(mUpdateResults);
		t.start();
    }
    
    final Runnable mUpdateResults = new Runnable() {
		public void run() {
			if(Utils.isNetwork(Lolkor.this)){
				process("http://www.leagueoflegends.co.kr/main.php");	
	            new Thread(new Runnable() {
	                @Override
	                public void run() {    
	                    runOnUiThread(new Runnable(){
	                        @Override
	                         public void run() {
	                        	update();
	                        	boolean rota_error = false;
	                    		for(int j = 0; j < rota_index.length; j++){
	                    			if(rota_index[j] == -1){
	                    				rota_error = true;
	                    			}
	                    		}
	                    		if(rota_error){
	                        		TextView tv = (TextView)findViewById(R.id.tv_system_check);
	                        		tv.setVisibility(View.VISIBLE);	
	                    		}
	                         }
	                    });
	                }
	            }).start(); 
			}else{
        		TextView tv = (TextView)findViewById(R.id.tv_system_check);
        		tv.setVisibility(View.VISIBLE);	
			}
		}

	};
	public void process(String url){
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost get = new HttpPost();
			get.setURI(new URI("http://ghdnjs9012.com/Rotation.php"));

			List<NameValuePair> params = new ArrayList<NameValuePair>();

			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
			get.setEntity(entity);

			HttpResponse resp = client.execute(get);
			BufferedReader br = new BufferedReader(new InputStreamReader(resp
					.getEntity().getContent()));
			String str = null;
			StringBuilder sb = new StringBuilder();

			while ((str = br.readLine()) != null) {
				sb.append(str).append("\n");
			}
			br.close();
			String rotation = sb.toString();
	        StringTokenizer st = new StringTokenizer(rotation, ";");
	        for(int i = 0; i < 10; i++){
	        	rota_index[i] = Integer.parseInt(st.nextToken());
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	public void process(String url){
		try {
			int rote_index = 0;
			Source source = new Source(new URL(url));
			List<Element> sss = source.getAllElements(HTMLElementName.DIV);
			for(int i = 0; i < sss.size(); i++){
		    	String ss = sss.get(i).getAttributeValue("class");
		    	if(ss == null){
		    		continue;
		    	}
		    	if(ss.equals("mian_champion")){
		    		rote_index = i;
		    		break;
		    	}
			}
	    	Element atags = source.getAllElements(HTMLElementName.DIV).get(rote_index);
	    	int champ_index = 0;
			for(int i = 0; i < atags.getAllElements().size(); i++){
		    	if(atags.getAllElements().get(i).getAttributeValue("href") != null){
					if(atags.getAllElements().get(i).getAttributeValue("href").length() < 38){
						continue;
					}

					if(atags.getAllElements().get(i).getAttributeValue("href").substring(0, 37).equals("./GameInfo/info_champion_sub.php?idx=")){
						 rota_index[champ_index] = Integer.parseInt(atags.getAllElements().get(i).getAttributeValue("href").substring(37, atags.getAllElements().get(i).getAttributeValue("href").length()));
						 champ_index++;
					}
		    	}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	*/
	  public void update(){
	    	for(int i = 0; i < 10; i++){
	    		ImageView iv = (ImageView)findViewById(R.id.rotation_00+(i*2));
	    		TextView tv = (TextView)findViewById(R.id.tv_ro_00+(i*2));
	    		for(int j = 0; j < ChampionData.champions.size(); j++){
	    			if(ChampionData.champions.get(j).champ_id == rota_index[i]){
	    				String path = "champ_img/"+ChampionData.champions.get(j).name_en+".jpg";
	    				try {
	    					iv.setImageDrawable(Drawable.createFromStream(getAssets().open(path),"src"));
	    				} catch (IOException e) {
	    					// TODO Auto-generated catch block
	    					e.printStackTrace();
	    				}
	    				iv.setTag((int)j);
	    				iv.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View v) {
				        		Intent intent = new Intent(Lolkor.this, Champion.class);
	                			intent.putExtra("champId", ""+v.getTag());
	                    		startActivity(intent);
							}
	    					
	    				});
	    				tv.setText(ChampionData.champions.get(j).name_en);
	    				break;
	    			}
	    		}
	    	}
	    }
    
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			new AlertDialog.Builder(Lolkor.this)
			.setTitle("LOLDictionary")
			.setMessage("You Want Exit?")
			.setIcon(R.drawable.icon)
			.setPositiveButton("Yes", new android.content.DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					android.os.Process.killProcess(android.os.Process.myPid()); 
					
				}
				
			})
			.setNegativeButton("No", new android.content.DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
				
			})
			.show();
		}else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
			AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
			int volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
			audio.setStreamVolume(AudioManager.STREAM_MUSIC, ++volume, AudioManager.FLAG_SHOW_UI);	
		}else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
			AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
			int volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
			audio.setStreamVolume(AudioManager.STREAM_MUSIC, --volume, AudioManager.FLAG_SHOW_UI);
		}else if(keyCode == KeyEvent.KEYCODE_MENU){
			return false;
		}
		return true;
	}
	
	public String loadUpdate() throws IOException {
		AssetManager assetManager = this.getResources().getAssets();
		AssetInputStream ais = (AssetInputStream)assetManager.open("update.txt"); 
        BufferedReader br = new BufferedReader(new InputStreamReader(ais));
        String line;
        StringBuilder data = new StringBuilder();
        while((line=br.readLine()) != null){
        	data.append(line);
        	data.append("\r\n");
        }
        return data.toString();
	}
	
    @Override
    public void onClick(View v) {
    	Intent intent;
    	switch(v.getId()){
    	case R.id.champion_info:
    		intent = new Intent(this, ChampionList.class);
    		this.startActivity(intent);
    		break;
    	case R.id.item_info:
    		intent = new Intent(this, ItemMenu.class);
    		this.startActivity(intent);
    		break;
    	case R.id.mastery_info:
    		intent = new Intent(this, Masteries.class);
    		this.startActivity(intent);
    		break;
    	case R.id.spells_info:
    		intent = new Intent(this, SummonerSpells.class);
    		this.startActivity(intent);
    		break;
    	case R.id.champ_gallery:
    		intent = new Intent(Lolkor.this, ChampionList.class);
    		intent.putExtra("list", "gallery");
			Lolkor.this.startActivity(intent); 
    		break;
    	case R.id.server_status:
    		intent = new Intent(Lolkor.this, ServerStatus.class);
			Lolkor.this.startActivity(intent);       
    		break;
    	case R.id.builder:
    		intent = new Intent(Lolkor.this, Builder.class);
			Lolkor.this.startActivity(intent);       
    		break;
    	case R.id.jugle_timer:
    		intent = new Intent(Lolkor.this, JungleTimer.class);
			Lolkor.this.startActivity(intent);       
    		break;
    	case R.id.option:
    		intent = new Intent(Lolkor.this, Option.class);
			Lolkor.this.startActivity(intent); 
    		break;
    	case R.id.ranking:
    		intent = new Intent(Lolkor.this, RankingBoard.class);
			Lolkor.this.startActivity(intent); 
    		break;
    	}
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, 1, 0, "Funny Card Turn");   
		boolean result = super.onCreateOptionsMenu(menu);
		return result;   
	} 
	
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = new Intent(this, CardTurn.class);
		this.startActivity(intent);
		return ( super.onOptionsItemSelected(item)); 
	}
}